poj 2513 trie树

题目大意:

输入木棒两端的颜色,一端颜色相同的木棒才能连接,问最后能不能连接成一根木棒

思路:

欧拉回路:如果图G中的一个路径包括每个边恰好一次,则该路径称为欧拉路径,如果一个回路是欧拉路径,则称为欧拉回路

无向图存在欧拉回路的充要条件
一个无向图存在欧拉回路,当且仅当该图所有顶点度数都为偶数,且该图是连通图。
有向图存在欧拉回路的充要条件
一个有向图存在欧拉回路,所有顶点的入度等于出度且该图是连通图。

本题用并查集判断是不是连通图,用TRIE树对应颜色相应的编号(map超时)


Sample Input

blue red
red violet
cyan blue
blue magenta
magenta cyan

Sample Output

Possible
#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <string>
#include <string.h>
#include <queue>
using namespace std;
const int MAXN = 500010;
struct tree {
	int id;
	tree* next[30];
	tree() {
		id = 0;
		memset(next, NULL, sizeof(next));
	}
};
int father[MAXN];
int d[MAXN] = { 0 };
tree* root = new tree;
int color = 0;
int find(int x) {
	if (father[x] == x)return x;
	return father[x] = find(father[x]);
}
void merge(int a, int b) {
	father[find(a)] = find(b);
}
int insert(char s[]) {
	tree* p = root;
	int l = strlen(s);
	for (int i = 0; i < l; i++) {
		if (p->next[s[i] - 'a'] == NULL) {
			p->next[s[i] - 'a'] = new tree;
		}
		p = p->next[s[i] - 'a'];
	}
	if (p->id != 0)return p->id;
	else {
		p->id = ++color;
		return p->id;
	}
}
int main() {
	char a[30], b[30];
	for (int i = 0; i < MAXN; i++)father[i] = i;
	while (scanf("%s %s",a,b)!=EOF) {
		int x = insert(a);
		int y = insert(b);
		merge(x, y);
		d[x]++;
		d[y]++;
	}
	int num1 = 0, num2 = 0;
	for (int i = 1; i <= color; i++) {
		if (father[i] == i)num1++;
		if (d[i] % 2 != 0)num2++;
	}
	//cout << num1 << " " << num2 << endl;
	if (num1 > 1 || (num2 != 2&&num2!=0))cout << "Impossible" << endl;
	else cout << "Possible" << endl;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值